<?php defined('SYSPATH') or die('No direct script access.');

class Model_Main
{
    /*
    * Закачиваем картинку на сервер
    * 
    * Имя инпута, директория, ширина, имя
    * 
    * Пример вызова - upload_image('image', 'media/uploads/articles/')
    * 
    * Возврат - либо имя картинки, либо null
    */
	public static function upload_image($input_name, $directory, $width = null, $filename = null)
    {
        $array = Validation::factory($_FILES);
        
        $array->rule($input_name, 'Upload::not_empty');            
        if ($array->check()) {                    
            // Закачиваем на сервер
            if(!$filename) {
                $filename = time().mt_rand(0, 1000).'.jpg';
            }
                
            $tmp_filename = Upload::save($_FILES[$input_name], $filename, $directory, 0755);
            
            // Закачали, теперь изменим размер            
            if ($width) {
               $image = Image::factory($tmp_filename); 
               $image->resize($width, null)->save();
            }
        } else {
            $filename = null;
        }
        
        return $filename;
    }
    
    public static function translit($str)
    {
        $tr = array(
            "А"=>"a","Б"=>"b","В"=>"v","Г"=>"g",
            "Д"=>"d","Е"=>"e","Ж"=>"j","З"=>"z","И"=>"i",
            "Й"=>"y","К"=>"k","Л"=>"l","М"=>"m","Н"=>"n",
            "О"=>"o","П"=>"p","Р"=>"r","С"=>"s","Т"=>"t",
            "У"=>"u","Ф"=>"f","Х"=>"h","Ц"=>"ts","Ч"=>"ch",
            "Ш"=>"sh","Щ"=>"sch","Ъ"=>"","Ы"=>"yi","Ь"=>"",
            "Э"=>"e","Ю"=>"yu","Я"=>"ya","а"=>"a","б"=>"b",
            "в"=>"v","г"=>"g","д"=>"d","е"=>"e","ж"=>"j",
            "з"=>"z","и"=>"i","й"=>"y","к"=>"k","л"=>"l",
            "м"=>"m","н"=>"n","о"=>"o","п"=>"p","р"=>"r",
            "с"=>"s","т"=>"t","у"=>"u","ф"=>"f","х"=>"h",
            "ц"=>"ts","ч"=>"ch","ш"=>"sh","щ"=>"sch","ъ"=>"y",
            "ы"=>"yi","ь"=>"","э"=>"e","ю"=>"yu","я"=>"ya", 
            " "=> "-", "."=> "", "?" => "", "!" => "", "/"=> "-"
        );
        
        $result = strtr($str, $tr);     
        if (preg_match('/[^A-Za-z0-9_\-]/', $result)) {
            $result = preg_replace('/[^A-Za-z0-9_\-]/', '', $result);
        }    
        $result = str_replace('--', '-', $result);    
        return strtolower($result);   
    }
    
    /*
    * Преобразует массив - ставит ключом элементов саммива id этого элемента
    * 
    * Пример - было {'0' => array('id' => 1, ...)}
    * стало         {'1' => array('id' => 1, ...)}
    */ 
    public static function process_array($array)
    {
        $result = array();
        foreach ($array as $item) {
            $result[$item->id] = $item;    
        }      
        return $result;  
    }
    
    public static function get_array($data)
    {
        $array = array();
        foreach ($data as $item) {
            $array[] = $item;   
        }          
        return $array;
    }
    
    // Делает первую букву заглавной
    public static function ucfirst_utf8($str)
    {
        $fc = mb_strtoupper(mb_substr($str, 0, 1));
        return $fc.mb_substr($str, 1);   
    }
	
	// Делает первую букву строчной
    public static function lcfirst_utf8($str)
    {
        $fc = mb_strtolower(mb_substr($str, 0, 1));
        return $fc.mb_substr($str, 1);   
    }
    
    public static function words_ucfirst($str)
    {
        $result = array();
        $words  = explode(' ', $str);
        foreach ($words as $word) {
            $result[] = self::ucfirst_utf8($word);    
        }
        return implode(' ', $result);
    }
    
    public static function rand_phrase(array $cases, $seed)
    {
        mt_srand($seed);      
        $min = 0;
        $max = count($cases) - 1;        
        $n = mt_rand($min, $max);    
        return $cases[$n];
    }
    
    public static function get_clean_name($name)
    {
        $name = mb_strtolower($name);
        //$name = preg_replace('/\s/i', '', $name);
        $name = str_replace(array('-', '(', ')', '.', '+', '"', '*', '/', '\\', '|', ','), '', $name);
        return $name;   
    }
    
    public static function get_csrf_token()
    {
        $token = md5(uniqid(mt_rand() . microtime()));
        Session::instance()->set('token', $token);
        return $token;      
    }
    
    public static function check_csrf_token()
    {
        $token = Request::current()->post('token') ? Request::current()->post('token') : null;
        if (!$token) {
            $token = Request::current()->param('token') ? Request::current()->param('token') : null;    
        }
        if (!$token) {
            throw new Model_Exception('Вероятна подделка запроса, вернитесь назад или попробуйте обновить страницу');
        }
        if (Session::instance()->get('token', null) == $token) {
            return true;    
        }
        throw new Model_Exception('Вероятна подделка запроса, вернитесь назад или попробуйте обновить страницу');
    }
    
    public static function reverse_array($array)
    {
        $result = array();
        foreach ($array as $key => $value) {
            $result[$value] = $key;    
        }    
        return $result;
    }
    
    public static function get_host_url($with_http = true)
    {
        $url = 'cashbackdoc.com';
        if ($with_http) {
            $url = 'http://'.$url;        
        }
        return $url;    
    }
    
    /*public static function get_static_host_url($with_http = true)
    {
        return null;
        $url = 'static.buzilio.ru';
        if ($with_http) {
            $url = 'http://'.$url;        
        }
        return $url;
    }  */
    
    public static function is_production_host()
    {
        if (strstr($_SERVER['HTTP_HOST'], self::get_host_url(false)) !== false) {
            return true;
        }
        return false;
    }
    
    public static function replace_macroses($text, $macroses)
    {
        foreach ($macroses as $macros => $value) {
            $text = str_replace('%'.$macros.'%', $value, $text);    
        } 
        return $text;  
    }
    
    public static function text_generator($text, $seed)
    {
        static $result;
        while (preg_match("/^(.*)\{([^\{\}]+)\}(.*)$/isU", $text, $matches)) {
            $p = explode('|', $matches[2]);
            $p = self::rand_phrase($p, $seed++);
            $text = $matches[1].$p.$matches[3]; 
        }
        return $text;
    }
    
    /*public static function text_generator($text, $seed)
    {
        static $result;
        if (preg_match("/^(.*)\{([^\{\}]+)\}(.*)$/isU", $text, $matches)) {
            $p = explode('|', $matches[2]);
            foreach ($p as $comb) {
                echo $matches[1].$comb.$matches[3].'<br />';
                //self::text_generator($matches[1].$comb.$matches[3]);
            }
        } else {
            $result[] = $text;
            return 0;
        }
        return array_values(array_unique($result));
    } */
    
    public static function get_subid($product = null, $coupon = null, $shop = null)
    {
        $site = self::get_host_url(false);
        $site = str_replace(array('.com', '.ru'), '', $site);
        
        $subid = '';
        if (isset($_COOKIE['subid']) && $_COOKIE['subid']) {
            $subid = str_replace('|', '', $_COOKIE['subid']);    
        }
        
        $product_id = '';
        if ($product) {
            $product_id = $product->id;    
        }
        
        $coupon_id = '';
        if ($coupon) {
            $coupon_id = $coupon->id;   
        }
        
        $cashback_id = '';
        $user = Model_Auth::instance()->get_user();
        if ($user) {
            if (!$shop) {
                $shop_id = null;
                if ($product) {
                    $shop_id = $product->shop_id;    
                } 
                if ($coupon) {
                    $shop_id = $coupon->shop_id;    
                } 
                $shop = ORM::factory('shop', $shop_id);  
            }
            if ($shop->cashback_payment_size) {
                $cashback_id = $user->id;    
            }   
        }
        
        $recommend_id = '';
        if (isset($_COOKIE['recommend']) && $_COOKIE['recommend']) {
            $recommend_id = $_COOKIE['recommend'];    
        }
        
        $pattern = '[site]|[subid]|[product_id]|[coupon_id]|[cashback_id]|[recommend_id]';
        return str_replace(array('[site]', '[subid]', '[product_id]', '[coupon_id]', '[cashback_id]', '[recommend_id]',),
                           array($site, $subid, $product_id, $coupon_id, $cashback_id, $recommend_id), $pattern);    
    }
    
    /**
    * Возвращает a или b в зависимости от переданной вероятности
    * 
    * @param mixed $a_probability
    * @param mixed $b_probability
    */
    public static function split_test($probabilities)
    {
        $a_probability = $probabilities[0];
        $b_probability = $probabilities[1]; 
        
        $n = rand(0, 100);
        if ($n < $a_probability) {
            return 'a';    
        }  
        return 'b';  
    }
    
    public static function get_utm_marks()
    {
        // utm_source=vkfashion&utm_medium=vk&utm_campaign=1
        $result = array();
        if (isset($_GET['utm_source']) && $_GET['utm_source']) {
            $result[] = 'utm_source='.$_GET['utm_source'];    
        }
        if (isset($_GET['utm_medium']) && $_GET['utm_medium']) {
            $result[] = 'utm_medium='.$_GET['utm_medium'];    
        }
        if (isset($_GET['utm_campaign']) && $_GET['utm_campaign']) {
            $result[] = 'utm_campaign='.$_GET['utm_campaign'];    
        }
        return implode(';', $result);
    }
}
